<template>
  <div
    v-if="!initializing"
    v-resize="resize"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  >
    <div ref="chartDiv" class="vc-echarts-radar" :style="style"></div>
  </div>
  <div
    v-else
    v-loading="true"
    element-loading-text=""
    style="min-height: 30px;"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  ></div>
</template>

<script setup>
import { ref, onMounted, computed, inject, getCurrentInstance, markRaw, nextTick, onUnmounted } from 'vue';
import * as echarts from "echarts";
import visual from "@/visual/js/visual";
import EventHandler from "@/visual/js/event";
import * as chart from "@/visual/js/echarts";
import JSON5 from 'json5';
import {parseColors} from "@/utils/color";
import tool from "@/utils/tool";

const props = defineProps({
  node: Object
});

const chartDiv = ref();
const currChart = ref(null);
const initializing = ref(true);
const currNode = ref(props.node);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);

const init = async(styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  await nextTick(() => initializing.value = false);
};

const loadData = tool.debounce(async() => {
  if (!chartDiv.value) return;
  const compStyle = currNode.value.currCompStyle || {};
  const compData = currNode.value.compData || {};
  let defaultOption = {};
  try {
    defaultOption = JSON5.parse(compStyle['jsonOption'] || '{}');
  } catch (e) {
    console.log("jsonOption解释出错", e)
  }

  const dataList = (await visual.loadData(
    compData,
    eventHandler,
    getData(),
    currNode.value)).data || [];

  const indicatorData = [];
  const legendData = [];
  const seriesData = [];
  const maxField = (compStyle.seriesList || []).find(item => item.dataType === 'maxValue');
  (compStyle.seriesList || []).forEach(item => {
    if (item.dataType === 'label') {
      for (let i=0; i<dataList.length; i++) {
        indicatorData.push({
          name: dataList[i][item.prop],
          max: maxField && maxField.prop && dataList[i][maxField.prop] || 100
        });
      }
    } else if (item.dataType === 'series') {
      const fieldData = [];

      for (let i=0; i<dataList.length; i++) {
        fieldData[i] = dataList[i][item.prop];
      }

      legendData.push(item.name);
      seriesData.push({
        name: item.name,
        data: [{
          name: item.name,
          value: fieldData
        }],
        ...parseRadar(compStyle)
      });
    }
  });

  const option = {
    animation: compStyle['animation'] || false,
    color: parseColors(compStyle['colorScheme']),
    title: chart.parseTitle(compStyle),
    toolbox: chart.parseToolbox(compStyle),
    tooltip: chart.parseTooltip(compStyle),
    legend: chart.parseLegend(compStyle, legendData),
    radar: {
      ...parseRadar(compStyle),
      indicator: indicatorData,
    },
    series: seriesData
  };

  await nextTick(() => {
    if (!chartDiv.value) return;
    if (currChart.value) currChart.value.dispose();
    currChart.value = markRaw(echarts.init(chartDiv.value));
    currChart.value.setOption(Object.assign({}, option, defaultOption));
    currChart.value.on('click', 'series', function(params) {
      const data = {};
      data['系列名'] = params.name;
      data['系列值'] = params.value;
      eventHandler.trigger("点击数据项事件", data);
    });
  });
  resize();
});

const parseRadar = (compStyle) => {
  const result = { type: 'radar' };

  result['radius'] = compStyle['series.radius'] || '75%';
  result['symbol'] = compStyle['series.symbol'] || 'none';
  result['symbolSize'] = compStyle['series.symbolSize'] || 4;
  if (compStyle['series.area']) {
    result['areaStyle'] = {
      opacity: compStyle['series.area.opacity']
    };
  }

  result['axisName'] = {
    show: !!compStyle['series.axisName'],
    color: compStyle['series.axisName.color'] || '#333'
  };

  result['axisLine'] = {
    show: !!compStyle['series.axisLine'],
    lineStyle: {
      color: compStyle['series.axisLine.color'] || '#ccc'
    }
  };

  result['splitLine'] = {
    show: !!compStyle['series.splitLine'],
    lineStyle: {
      color: compStyle['series.splitLine.color'] || '#ccc'
    }
  };

  return result;
};

const style = computed(() => {
  const compStyle = currNode.value.currCompStyle || {};

  let result = '';
  result += visual.parseTpl('width: {value};', compStyle['width']);
  result += visual.parseTpl('height: {value};', compStyle['height']);
  return result;
});

const getData = () => {
  return {
    inputParam: currNode.value.inputParam || {}
  };
};

const changeStyle = (styleId) => {
  init(styleId);
};

const refresh = async() => {
  await init();
  loadData();
};

const resize = () => {
  try {
    currChart.value.resize();
  } catch (e) {
    console.log(e);
  }
};

onMounted(async() => {
  await init();
  loadData();
});

onUnmounted(() => {
  eventHandler.unregister();
});

defineExpose({ getData, changeStyle, refresh, loadData });
</script>